#!/bin/bash

echo "🔍 SPAM3UK 环境诊断脚本"
echo "========================"
echo "检查时间: $(date)"
echo ""

echo "📋 基本系统信息"
echo "----------------------------------------"
echo "操作系统: $(uname -a)"
echo "主机名: $(hostname)"
echo "用户: $(whoami)"
echo ""

echo "🐹 Go环境信息"  
echo "----------------------------------------"
go version
echo "GOOS: $(go env GOOS)"
echo "GOARCH: $(go env GOARCH)"
echo ""

echo "🌐 网络环境检查"
echo "----------------------------------------"
echo "本机IP: $(curl -s ifconfig.me || echo '无法获取')"
echo "DNS服务器: $(cat /etc/resolv.conf | grep nameserver | head -3)"
echo ""

echo "🎯 Ford网站连接测试"
echo "----------------------------------------"
echo "DNS解析:"
dig +short www.ford.co.uk 2>/dev/null || nslookup www.ford.co.uk
echo ""

echo "延迟测试:"
for i in {1..3}; do
    echo "  测试 $i: $(curl -o /dev/null -s -w '%{time_total}s' https://www.ford.co.uk/cars)"
done
echo ""

echo "HTTP版本检测:"
curl -I -s https://www.ford.co.uk/cars | grep -i "server\|http"
echo ""

echo "🔧 TLS/SSL信息"
echo "----------------------------------------"
openssl version 2>/dev/null || echo "OpenSSL未安装"
echo ""

echo "📦 Chrome/Chromium检查"
echo "----------------------------------------"
if command -v google-chrome &> /dev/null; then
    google-chrome --version
elif command -v chromium-browser &> /dev/null; then
    chromium-browser --version
elif command -v chromium &> /dev/null; then
    chromium --version
else
    echo "未找到Chrome/Chromium"
fi
echo ""

echo "🚀 Go HTTP/2测试"
echo "----------------------------------------"
cat > test_http_client.go << 'EOF'
package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
    "time"
)

func main() {
    // 测试默认HTTP客户端
    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Get("https://www.ford.co.uk/cars")
    if err != nil {
        fmt.Printf("默认客户端错误: %v\n", err)
    } else {
        fmt.Printf("默认客户端成功: %s, 协议: %s\n", resp.Status, resp.Proto)
        resp.Body.Close()
    }
    
    // 测试强制HTTP/1.1
    tr := &http.Transport{
        ForceAttemptHTTP2: false,
        TLSClientConfig: &tls.Config{},
    }
    client2 := &http.Client{Transport: tr, Timeout: 10 * time.Second}
    resp2, err2 := client2.Get("https://www.ford.co.uk/cars")
    if err2 != nil {
        fmt.Printf("HTTP/1.1客户端错误: %v\n", err2)
    } else {
        fmt.Printf("HTTP/1.1客户端成功: %s, 协议: %s\n", resp2.Status, resp2.Proto)
        resp2.Body.Close()
    }
}
EOF

echo "编译并运行HTTP测试..."
if go run test_http_client.go; then
    echo "✅ Go HTTP测试完成"
else
    echo "❌ Go HTTP测试失败"
fi

rm -f test_http_client.go

echo ""
echo "✨ 环境诊断完成"
echo "========================"
